package com.gem.talkbase.fragment;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import com.gem.talkbase.R;
import com.gem.talkbase.activity.ChatMessageService;
import com.gem.talkbase.activity.Chat_Activity;
import com.gem.talkbase.activity.HelpActivity;
import com.gem.talkbase.adapter.RecentChatAdapter;
import com.gem.talkbase.bean.ChatMsg;
import com.gem.talkbase.bean.FirendMsg;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.service.JSON_GetFriendMsgList;
import com.gem.talkbase.widget.BaseSwipeListViewListener;
import com.gem.talkbase.widget.SwipeListView;
import com.gem.talkbase.widget.TitleView;
import com.gem.talkbase.bean.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;


/**
 * 
 * 功能描述：首页fragment页面
 */
public class Fragment_message extends Fragment {
	 //定义底部显示
	private View mParent;
	 String userid;
	//定义fragment布局
	private FragmentActivity mActivity;
	//定义顶部显示
	private TitleView mTitle;
	//定义fragment里面显示的内容
	private TextView mText;
	private SwipeListView mSwipeListView ,mSwipeListView2;
	private RecentChatAdapter mRecentChatAdapter,mRecentChatAdapter2;
	private String friendid,friendname,date,msgString;
	private  List<ChatMsg> listMsg =  new ArrayList<ChatMsg>();
	private  List<FirendMsg> listMsg2 =  new ArrayList<FirendMsg>();
	private  List<FirendMsg> listMsg3 =  new ArrayList<FirendMsg>();
	private List<FirendMsg> list,list1;
	List<ChatMsg> list3=new ArrayList<ChatMsg>();
	MyBroadcastReceiver br;
	String requestPath=Client.Firend_Msg;
	String getfirendPath=Client.Firend_getAllMsg;
	SharedPreferences sharedPreferences; 
	final String firendid=null;
	
	/**
	 * Create a new instance of DetailsFragment, initialized to show the text at
	 * 'index'.
	 */
	public Fragment_message(){
		
	}
	public static Fragment_message newInstance(int index) {
		Fragment_message f = new Fragment_message();

		// Supply index input as an argument.
		Bundle args = new Bundle();   
		args.putInt("index", index);
		f.setArguments(args);

		return f;
	}

	public int getShownIndex() {
		return getArguments().getInt("index", 0);
	}
	
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
	
//	    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//            Log.i("---Intent.ACTION_SCREEN_OFF---", "---receiving---");
//    // 将当前service停掉，并注销当前BroadcastReceiver
//            ChatMessageService.st;
    
}

//
//	@Override
//	public void onPause() {  
//		// TODO Auto-generated method stub
//		super.onPause();
//	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		System.out.println("注册广播================================");
		IntentFilter myIntentFilter = new IntentFilter();   
        myIntentFilter.addAction("com.gem.talkbase");
        br=new MyBroadcastReceiver();
        getActivity().registerReceiver(br, myIntentFilter);
	
	}
	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sharedPreferences =getActivity().getSharedPreferences(Client.SAVE_USER,getActivity().MODE_PRIVATE);
//		
//		IntentFilter myIntentFilter = new IntentFilter();   
//        myIntentFilter.addAction("com.gem.talkbase");
//        br=new MyBroadcastReceiver();
//        getActivity().registerReceiver(br, myIntentFilter);
//	
	}
   
//	private FragmentActivity getApplicationContext() {
//		// TODO Auto-generated method stub
//		return getActivity();
//	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		//R.layout.fragment_home:点击底部图标后，界面显示的布局
		
		View view = inflater.inflate(R.layout.fragment_message, container, false);
		
 
		System.out.println("=======================friendid======================"+friendid);

		mSwipeListView = (SwipeListView) view
				.findViewById(R.id.recent_listview);
		mSwipeListView.setEmptyView(view.findViewById(R.id.recent_empty));
		System.out.println("执行时========================================");
		mSwipeListView.setSwipeListViewListener(mSwipeListViewListener);
		
	    final String userid = sharedPreferences.getString("userid", "");   
	    AjaxParams params = new AjaxParams();
		params.put("login_id", userid);
		FinalHttp fh = new FinalHttp();
		fh.post(getfirendPath, params, new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, String strMsg) {
				System.out.println("加载失败！！！");
				super.onFailure(t, strMsg);
			}
			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				System.out.println("正在加载！！！");
				super.onLoading(count, current);
			}
		
			@Override
			public void onSuccess(String jsonString) {
	 			super.onSuccess(jsonString);  
	 			list=new ArrayList<FirendMsg>();
	 			JSON_GetFriendMsgList json_GetFriendMsgList=new JSON_GetFriendMsgList();
	 			list=json_GetFriendMsgList.fun(jsonString);
	 			Iterator<FirendMsg> iterator=list.iterator();	
	 			String firenddate = null,firendmsg = null,firendnuick= null,firendimage,firendid;
	 			while (iterator.hasNext()) {
					FirendMsg firendMsg = (FirendMsg) iterator.next();
					firendid=firendMsg.getFirendid();
			        firenddate=firendMsg.getDate();
					firendmsg=firendMsg.getMsg();
					firendnuick=firendMsg.getUnick();
					firendimage=firendMsg.getUimage();
					FirendMsg firendMsg2=new FirendMsg(firendid,firendnuick,firendimage,firendmsg,firenddate);
				    listMsg2.add(firendMsg2);
					  System.out.println("===========>>>>"+firendnuick+"-----"+firendmsg+"------"+firendid);
				}
	 	      //  System.out.println("===========>>>>"+firendnuick+"-----"+firendmsg+"------"+firenddate);
			    System.out.println(listMsg+"================listMsg");
			    mRecentChatAdapter=new RecentChatAdapter(getActivity(),listMsg2,userid);
				mSwipeListView.setAdapter(mRecentChatAdapter);
				mRecentChatAdapter.notifyDataSetChanged();
				
			  }
		});
	    
		return view;
	}
	
	BaseSwipeListViewListener mSwipeListViewListener = new BaseSwipeListViewListener() {
		
		@Override
		public void onClickFrontView(int position) {
			 super.onClickFrontView(position);
		
			 FirendMsg firendMsg=(FirendMsg) mRecentChatAdapter.getItem(position);
			
			 String msg=firendMsg.getMsg();
			 String uid=firendMsg.getUnick();
			 String fid=firendMsg.getFirendid();
			 String fimage=firendMsg.getUimage();
		     System.out.println(msg+"OOOOOOOOO"+fid+"OOOOOOOOO"+uid);
             Intent intent=new Intent(getActivity(), Chat_Activity.class);
             intent.putExtra("friend_unick",uid);//这是好友的昵称
             intent.putExtra("friend_id",fid);//这是好友id
             intent.putExtra("friend_msg",msg);//这是好友的昵称
             intent.putExtra("friend_image",fimage);//这是好友的昵称
             startActivity(intent);
		}

		@Override
		public void onClickBackView(int position) {
			mSwipeListView.closeOpenedItems();// 关闭打开的项
		}
	};

	public void fun2(final String userid){
		 AjaxParams params = new AjaxParams();
			params.put("login_id", userid);
			FinalHttp fh = new FinalHttp();
			fh.post(getfirendPath, params, new AjaxCallBack<String>() {
				@Override
				public void onFailure(Throwable t, String strMsg) {
					System.out.println("加载失败！！！");
					super.onFailure(t, strMsg);
				}
				@Override
				public void onLoading(long count, long current) {
					// TODO Auto-generated method stub
					System.out.println("正在加载！！！");
					super.onLoading(count, current);
				}
			
				@Override
				public void onSuccess(String jsonString) {
		 			super.onSuccess(jsonString);
//		 			list=new ArrayList<FirendMsg>();
		 			listMsg2.clear();//清空上次里面的数据，就是数据库改变，及时刷新改变listView
		 			JSON_GetFriendMsgList json_GetFriendMsgList=new JSON_GetFriendMsgList();
		 			list=json_GetFriendMsgList.fun(jsonString);
		 			Iterator<FirendMsg> iterator=list.iterator();	
		 			String firenddate = null,firendmsg = null,firendnuick= null,firendimage,firendid;
		 			while (iterator.hasNext()) {
						FirendMsg firendMsg = (FirendMsg) iterator.next();
						firendid=firendMsg.getFirendid();
				        firenddate=firendMsg.getDate();
						firendmsg=firendMsg.getMsg();
						firendnuick=firendMsg.getUnick();
						firendimage=firendMsg.getUimage();
						FirendMsg firendMsg2=new FirendMsg(firendid,firendnuick,firendimage,firendmsg,firenddate);
					    listMsg2.add(firendMsg2);
						System.out.println("===========>>>>"+firendnuick+"-----"+firendmsg+"------"+firendid);
					}
		 	      //  System.out.println("===========>>>>"+firendnuick+"-----"+firendmsg+"------"+firenddate);
				    System.out.println(listMsg+"================listMsg");
                    System.out.println(getActivity()+"===================getActivity");
                   
				    mRecentChatAdapter=new RecentChatAdapter(getActivity(),listMsg2,userid);
					mSwipeListView.setAdapter(mRecentChatAdapter);
					mRecentChatAdapter.notifyDataSetChanged();
				  }
			});
	}

	public void fun(final String userid,final String firendid,String msg,final String date){
		
		AjaxParams params = new AjaxParams();
		params.put("username", userid);
		params.put("firendid", firendid);
		params.put("msg", msg);
		params.put("date", date);
		System.out.println(userid+"============="+msgString+"----------"+date);
		FinalHttp fh = new FinalHttp();
		fh.post(requestPath, params, new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, String strMsg) {
				System.out.println("加载失败！！！");
				super.onFailure(t, strMsg);   
			}
			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				System.out.println("正在加载！！！");
				super.onLoading(count, current);
			}
		
			@Override
			public void onSuccess(String jsonString) {
	 			super.onSuccess(jsonString);
	 			if (jsonString.length()>1) {
					System.out.println("输出了值===================");
					fun2(userid);
//				    Iterator<ChatMsg> it=listMsg.iterator();
//			    	while(it.hasNext()){
//			    		ChatMsg re= it.next();
//			    	
//			    		if(re.getUserid().equals(firendid)){  
//			         //
//			    			listMsg.remove(re);
//			    		}
//			    
//		    	}	 
//			    String userid = sharedPreferences.getString("userid", ""); 
//			    ChatMsg chatMsg=new ChatMsg(firendid,msgString,date);
//			    listMsg.add(chatMsg);
//			    System.out.println(listMsg+"================listMsg");
//			    mRecentChatAdapter=new RecentChatAdapter(getActivity(),listMsg,userid);
//				mSwipeListView.setAdapter(mRecentChatAdapter);
//				mRecentChatAdapter.notifyDataSetChanged();
				//	info(userid, firendid);
				} else {
					System.out.println("没有===================");
				}
			}
		});
	}
	
	
	public class MyBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
		
			final ChatMsg msg = (ChatMsg) intent.getSerializableExtra("message");
			if (msg != null) {//如果不是空，说明是消息广播
		    date=msg.getDate();//得到时间
		    msgString=msg.getMsg();//得到消息
		    final String firendid=msg.getUserid();//得到id	
		    userid = sharedPreferences.getString("userid", ""); 
		    System.out.println(userid+"==========================================userid");
		    fun(userid, firendid, msgString, date);//添加==========================
		    System.out.println(date+"+++++++++++++++++++"+msgString+"+++++++++++++++++"+firendid);


			
			
		
//		    Iterator<ChatMsg> it=listMsg.iterator();
//		    	while(it.hasNext()){
//		    		ChatMsg re= it.next();
//		    	
//		    		if(re.getUserid().equals(firendid)){  
//		         //
//		    			listMsg.remove(re);
//		    		}
//		    
//	    	}	 
//   
//		    ChatMsg chatMsg=new ChatMsg(msg.getUserid(),msg.getMsg(),msg.getDate());
//		    listMsg.add(chatMsg);
//		    System.out.println(listMsg+"================listMsg");
//		    mRecentChatAdapter=new RecentChatAdapter(getActivity(),listMsg,userid);
//			mSwipeListView.setAdapter(mRecentChatAdapter);
//			mSwipeListView.setSwipeListViewListener(mSwipeListViewListener);
//			mRecentChatAdapter.notifyDataSetChanged();
			} else {//如果是空消息，说明是关闭应用的广播
//				close();
			}
		} 
		
			  
    }
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mActivity = getActivity();//得到activity
		mParent = getView();//得到view
		 //得到第一个fragment
		mTitle = (TitleView) mParent.findViewById(R.id.title);
		//得到底部按钮的名字“消息”
		mTitle.setTitle(R.string.title_home);
		//设置顶部“退出”按钮名字和单击事件
//		mTitle.setLeftButton(R.string.exit, new OnLeftButtonClickListener(){
//
//			@Override
//			public void onClick(View button) {
//				mActivity.finish();
//			}
//			
//		});
//		mTitle.setRightButton(R.string.help, new OnRightButtonClickListener() {
//
//			@Override
//			public void onClick(View button) {
//				goHelpActivity();
//			}
//		});
		//跳转的同时实现中间的页面显示
//		mText = (TextView) mParent.findViewById(R.id.fragment_home_text);

	}
	//点击按钮跳转函数
	private void goHelpActivity() {
		Intent intent = new Intent(mActivity, HelpActivity.class);
		startActivity(intent);
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	    getActivity().unregisterReceiver(br);
		ChatMessageService chatMessageService=new ChatMessageService();
		chatMessageService.stopSelf();
	}

}
